'use strict';

const db = uniCloud.database();
const crypto = require('crypto');

exports.main = async (event, context) => {
  const { mobile, password, nickname, birthday, address, wx_openid, wx_unionid, code } = event;
  
  // 参数校验
  if (!mobile || !password) {
    return {
      code: 400,
      message: '手机号和密码为必填项'
    };
  }
  
  // 手机号格式校验
  const mobileRegex = /^1[3-9]\d{9}$/;
  if (!mobileRegex.test(mobile)) {
    return {
      code: 400,
      message: '手机号格式错误'
    };
  }
  
  // 密码长度校验
  if (password.length < 6) {
    return {
      code: 400,
      message: '密码长度不能少于6位'
    };
  }
  
  try {
    // 检查验证码
    if (code) {
      const codeCollection = db.collection('sms-codes');
      const codeRes = await codeCollection.where({
        mobile: mobile,
        code: code,
        type: 'register',
        used: false,
        expire_time: db.command.gt(new Date())
      }).get();
      
      if (codeRes.data.length === 0) {
        return {
          code: 400,
          message: '验证码无效或已过期'
        };
      }
      
      // 标记验证码已使用
      await codeCollection.doc(codeRes.data[0]._id).update({
        used: true
      });
    }
    
    // 检查手机号是否已注册
    const userCollection = db.collection('uni-id-users');
    const existUser = await userCollection.where({
      mobile: mobile
    }).get();
    
    if (existUser.data.length > 0) {
      return {
        code: 400,
        message: '该手机号已注册'
      };
    }
    
    // 密码加密
    const hashedPassword = crypto.createHash('md5').update(password + 'saltstring').digest('hex');
    
    // 构建用户数据
    const userData = {
      mobile: mobile,
      password: hashedPassword,
      nickname: nickname || `用户${mobile.substr(-4)}`,
      status: 0,
      register_date: new Date(),
      agree_privacy: true
    };
    
    // 添加可选字段
    if (birthday) {
      userData.birthday = new Date(birthday);
    }
    
    if (address) {
      userData.address = address;
    }
    
    if (wx_openid) {
      userData.wx_openid = wx_openid;
    }
    
    if (wx_unionid) {
      userData.wx_unionid = wx_unionid;
    }
    
    // 插入用户数据
    const result = await userCollection.add(userData);
    
    if (result.id) {
      return {
        code: 200,
        message: '注册成功',
        data: {
          uid: result.id,
          mobile: mobile,
          nickname: userData.nickname
        }
      };
    } else {
      return {
        code: 500,
        message: '注册失败，请重试'
      };
    }
    
  } catch (error) {
    console.error('用户注册错误：', error);
    return {
      code: 500,
      message: '服务器错误，请重试'
    };
  }
};